/**
 * Created by hcadmin on 16/11/28.
 */
$(function(){
    //全局变量
    var options_arr        = [];
    var options_str        = "";
    var choice_type;
    var isselect;
    var _this;
    var img_src            = "";
    //获取url传过来的数据
    //获取url的参数
    (function ($) {
        $.getUrlParam = function (name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            var r   = window.location.search.substr(1).match(reg);
            if (r != null) return unescape(r[2]); return null;
        }
    })(jQuery);
    //编辑模板是获取的参数
    var dailyrecord_temp_id = $.getUrlParam('dailyrecord_temp_id');
    var edit                = $.getUrlParam('edit');
    var sequence            = $.getUrlParam('sequence');
    var icon                = $.getUrlParam('icon');
    //点击创建模板时候传的参数
    var num_model           = $.getUrlParam('num_model');

    var whichpage           = $.getUrlParam('whichpage');

    //点击返回时  点击总返回   点击选类型返回
    $("#log_back").on('click',function(){
        window.history.back(-1);
    });
    $("#log_back_choice").on('click',function(){
        quitChoice();
    });


    //点击输入框
    $(document).on('focus','.field_input',function(e){

        var top = e.target.offsetParent.offsetTop;

        //if(top>300){
        //    if($(".blank_div").length==0){
        //        var html = "<div class='blank_div' style='width: 100%;height: 21.09375vh'></div>";
        //
        //        $('.down_navbar_div').append(html);
        //    }
        //}
        window.scrollTo(0,top);
    });
    $(document).on('focus','.right_text_big_option',function(e){

        var top = e.target.offsetTop;

        console.log(top);

        //if(top>300){
        //    if($(".blank_div").length==0){
        //        var html = "<div class='blank_div' style='width: 100%;height: 21.09375vh'></div>";
        //
        //        $('.down_navbar_div').append(html);
        //    }
        //}
        window.scrollTo(0,top);
    });


    //$(document).on('blur','.field_input',function(){
    //    $('.blank_div').remove();
    //});


    //画出选择行时 的html
    var field_real = "<div class='add_field_real'>" +
        "<div class='col-xs-2'>" +
        "<img src='../logImg/redMinus.png' class='redMinus_pic'>" +
        "</div>" +
        "<div class='col-xs-6 mid_cell'>" +
        "<input type='text' class='field_input' placeholder='请填写字段名称'>" +
        "</div>" +
        "<div class='col-xs-4 right_text'>" +
        "<div class='field_type' options='' is_necessary='1' type='0'>文本型(必填)</div>"+
        "<img src='../logImg/rightIcon.png' class='rightIcon_pic'>" +
        "</div></div>";

    //点击 增加模板字段
    $(".add_field").on('click',function(){
        $(".add_field_bigest").append(field_real);

        $(".field_input").last().focus();
    });
    $(document).on('click','.redMinus_pic',function(){
        $(this).parent().parent().remove();
    });
    //根据类型判断文字
    function typeName(a,b){
        var type = parseInt(a);
        var typeName;
        switch (type)
        {
            case  0:
                if(b==0){
                    typeName = "文本型";
                }else{
                    typeName = "文本型(必填)";
                }
                break;
            case  1:
                if(b==0){
                    typeName = "数字型";
                }else {
                    typeName = "数字型(必填)";
                }
                break;
            case  2:
                if(b==0){
                    typeName = "下拉型";
                }else {
                    typeName = "下拉型(必填)";
                }
                break;
            case  3:
                if(b==0){
                    typeName = "日期型";
                }else {
                    typeName = "日期型(必填)";
                }
                break;
            case  4:
                if(b==0){
                    typeName = "日期型";
                }else {
                    typeName = "日期型(必填)";
                }
                break;
            case  5:
                if(b==0){
                    typeName = "日期型";
                }else {
                    typeName = "日期型(必填)";
                }
                break;
            default:
                break;
        }
        return typeName;
    };
    //选择类型时的返回 和 确定
    function quitChoice(){
        //清楚已经选择的数据
        //----右打钩  时间选择  选项选择
        $(".create_model").show();
        $(".choice_modelType").hide();

        $(".left_tick_pic").hide();

        $(".three_time_bigest").hide();
        $("#1").attr('src','../../approval/approvalImg/choice_round.png');
        $("#2").attr('src','../../approval/approvalImg/unchoice_round.png');
        $("#3").attr('src','../../approval/approvalImg/unchoice_round.png');

        $(".add_option_bigest").hide();
        $(".add_option_content").remove();
        $(".add_option_text_real").remove();
    }
    //点击跳转选择类型页面
    $(document).on('click','.right_text',function(){
            _this        = $(this);
        var is_necessary = $(this).children(0).attr("is_necessary");
            isselect     = is_necessary;
        var options      = $(this).children(0).attr("options");
        var type         = $(this).children(0).attr("type");
            choice_type  = type;
        //判断是否必要
        if(is_necessary=="1"){
            $(".needOrNot_btn").attr('src','../logImg/open.png');
        }else{
            $(".needOrNot_btn").attr('src','../logImg/close.png');
        }
        //判断哪种类型  0-文本 1-数字 2-下拉 3-日期全 4-仅日期 5-仅时间
        if(type=="0"){
            $("#text_type").css("display","block");
        }
        else if(type=="1"){
            $("#num_type").css("display","block");
        }
        else if(type=="2"){
            $("#select_type").css("display","block");
            $(".add_option_bigest").show();

            console.log('options',options);
            console.log('options_arr',options_arr);

            if(options.length>0){
                options_arr  = options.split(",");
                for(var i=0;i<options_arr.length;i++){
                    var  html = "<div class='add_option_text_real'>" +
                        "<div class='left_tick_add'>" +
                        "<img src='../logImg/redCross.png' class='left_tick_pic_del'></div>" +
                        "<input class='right_text_big_option' placeholder='请输入' value='"+options_arr[i]+"'></div>";
                    $(".option_content").append(html);
                }
            }
        }
        else{
            $("#date_type").css("display","block");
            $(".three_time_bigest").show();
            if(type=="3"){
                $("#1").attr('src','../../approval/approvalImg/choice_round.png');
            }else if(type=="4"){
                $("#1").attr('src','../../approval/approvalImg/unchoice_round.png');
                $("#2").attr('src','../../approval/approvalImg/choice_round.png');
            }else{
                $("#1").attr('src','../../approval/approvalImg/unchoice_round.png');
                $("#3").attr('src','../../approval/approvalImg/choice_round.png');
            }
        }
        $(".create_model").hide();
        $(".choice_modelType").show();
    });
    //点击选择是否必要
    $(".needOrNot_btn").on('click',function(){
        if(isselect=="1"){
            $(".needOrNot_btn").attr("src","../logImg/close.png");
            isselect = "0";
        }else{
            $(".needOrNot_btn").attr("src","../logImg/open.png");
            isselect = "1";
        }
    });
    //点击选择类型 选项 日期
    $(".field_big").on('click',function(){
        $(".field_big").find(".left_tick_pic").css("display","none");
        $(this).children(0).children(0).css("display","block");
        choice_type = $(this).attr("choice_type");

        if($(this).attr("id")=="select_big"){
            $(".add_option_bigest").show();
            $(".three_time_bigest").hide();
        }else if($(this).attr("id")=="date_big"){
            $(".add_option_bigest").hide();
            $(".add_option_content").remove();
            $(".three_time_bigest").show();
        }else{
            $(".add_option_bigest").hide();
            $(".add_option_content").remove();
            $(".three_time_bigest").hide();
        }
    });
    $(".add_option_text").on('click',function(){
        var html = "<div class='add_option_text add_option_content'>" +
            "<div class='left_tick_add'>" +
            "<img src='../logImg/redCross.png' class='left_tick_pic_del'></div>" +
            "<input class='right_text_big_option' placeholder='请输入'></div>";
        $(".option_content").append(html);

        $('.right_text_big_option').last().focus();
    });
    $(".three_time_mid").on('click',function(){
        //设置三行 都为未选中  is_choice都为0
        $(".left_tick_pic_o").attr('src','../../approval/approvalImg/unchoice_round.png');
        //设置选中的 为选中图标 is_choice为1
        $(this).children(0).children(0).attr('src','../../approval/approvalImg/choice_round.png');
        choice_type = $(this).attr("choice_type");
    });
    //点击删除选择项
    $(document).on('click','.left_tick_pic_del',function(){
        $(this).parent().parent().remove();
    });
    //点击保存 类型
    $(".bottom_save_mid2").on('click',function(){
        if(choice_type=="2"){
            if($(".right_text_big_option").length>0){
                $(".right_text_big_option").each(function(index){
                    options_arr[index] = HTMLEncode($(this).val());
                });
                options_str = options_arr.join(",");
            }else{
                $(".call_back_success2").html("请添加备选项").show().fadeOut(2000);
                return;
            }
            if(options_arr.indexOf("")>-1){
                $(".call_back_success2").html("备选项不能为空").show().fadeOut(2000);
                return;
            }
        }
        $(_this).children(0).attr("is_necessary",isselect);
        $(_this).children(0).attr("options",options_str);
        $(_this).children(0).attr("type",choice_type);
        $(_this).children(0).html(typeName(choice_type,isselect));

        quitChoice();
    });


    //图片icon选择
    $(".col-xs-2").on('click',function(){
        img_src             = $(this).children(0).attr("src");
        $(".rounded_Rectangle").css("display","none");
        $(this).children(1).css("display","block");
    });


    //编辑模板
    if(edit==1){
        $.ajax({
            beforeSend:function(){
                $(".loading").show();
            },
            url:apiurl+"/dailyrecords/temp/"+dailyrecord_temp_id+"",
            type:"GET",
            success:function(d){
                $(".loading").hide();
                var data                    = JSON.parse(d).data;
                var dailyrecord_temp_title  = data.dailyrecord_temp_title;               //模板名称
                var dailyrecord_temp_icon   = data.dailyrecord_temp_icon;                //模板icon
                    img_src                 = dailyrecord_temp_icon;
                var fields                  = data.fields;

                //模板名称
                $(".model_name_input").val(dailyrecord_temp_title);

                //模板详情
                for(var i=0;i<fields.length-1;i++){
                    var type = fields[i].daiyrecord_temp_field_type;
                    var title = fields[i].dailyrecord_temp_field_title;
                    var options = fields[i].options;
                    var is_necessary = fields[i].is_necessary;
                    var dailyrecord_temp_field_id = fields[i].dailyrecord_temp_field_id;

                    var text_type = typeName(type,is_necessary);

                    var op_str="";
                    if(options!=""){
                        op_str=options;
                    }
                    var html = "<div class='add_field_real'>" +
                        "<div class='col-xs-2'>" +
                        "<img src='../logImg/redMinus.png' class='redMinus_pic'>" +
                        "</div>" +
                        "<div class='col-xs-6 mid_cell'>" +
                        "<input type='text' value='"+title+"' class='field_input' placeholder='请填写字段名称'>" +
                        "</div>" +
                        "<div class='col-xs-4 right_text'>" +
                        "<div class='field_type' options='"+op_str+"' is_necessary='"+is_necessary+"' type='"+type+"'>"+text_type+"</div>"+
                        "<img src='../logImg/rightIcon.png' class='rightIcon_pic'>" +
                        "</div></div>";

                    $(".add_field_bigest").append(html);
                }

                //模板icon
                $(".model_icon_pic").each(function(){
                    var src = $(this).attr("src");
                    if(src==dailyrecord_temp_icon){
                        $($(this).parent().find(".rounded_Rectangle")).css("display","block");
                    }
                });
            }
        });
    }

    //创建模板
    $(".bottom_save_mid").on('click',function(){


        var fields = [];
        var sequence_final = "";
        $('.field_type').each(function(index){
            var options_attr                = $(this).attr("options");
            var options;
            if(options_attr.length>0){
                options = options_attr;
            }else{
                options = "";
            }
            var sequence_num                = index+1;
            fields[index] = {
                dailyrecord_temp_field_title:HTMLEncode($($(this).parent().parent().children(0)[1]).children(0).val()),
                daiyrecord_temp_field_type:$(this).attr("type"),
                is_necessary : $(this).attr("is_necessary"),
                sequence :""+sequence_num+"",
                options :options
            };
            sequence_final = sequence_num+1;
        });
        var remarks = {
            dailyrecord_temp_field_title:"备注",
            daiyrecord_temp_field_type:"0",
            is_necessary:'0',
            sequence:""+sequence_final+"",
            options:""
        };
        fields.push(remarks);
        var sequence_a;
        if(edit==1){
            sequence_a = sequence;
        }else{
            dailyrecord_temp_id = "";
            sequence_a = num_model;
        }
        var title = HTMLEncode($(".model_name_input").val());
        var data={
            dailyrecord_temp_title:title,
            dailyrecord_temp_icon:img_src,
            dailyrecord_temp_status:"0",
            sequence:sequence_a,
            user_id:localStorage.user_id,
            group_id:localStorage.group_id,
            fields:fields
        };
        if(title==""){
            $(".call_back_success").html("请填写模板名称").show().fadeOut(2000);
            return;
        }

        var data_json = JSON.stringify(data);
        if($(".add_field_real").length>0){
            var field_input_arr = [];
            $(".field_input").each(function(index){
                field_input_arr[index] = HTMLEncode($(this).val());
            });
            if(field_input_arr.indexOf("")>-1){
                $(".call_back_success").html("字段名不能为空").show().fadeOut(2000);
                return;
            }
        }else{
            $(".call_back_success").html("请添加字段").show().fadeOut(2000);
            return;
        }

        if(img_src=="") {
            $(".call_back_success").html("请选择模板图标").show().fadeOut(2000);
            return;
        }
        //}else{
            $.ajax({
                beforeSend:function(){
                    $(".bottom_save_mid").html("正在保存...");
                },
                url:apiurl+"/dailyrecords/temp",
                type:"POST",
                data:{
                    jsonString:data_json,
                    dailyrecord_temp_id:dailyrecord_temp_id
                },
                success:function(d){
                    var call_back = JSON.parse(d);
                    if(call_back.code=="0"){
                        $(".bottom_save_mid").html("保存模板");
                        $(".call_back_success").html("提交成功").fadeIn(1000,function(){
                            if(dailyrecord_temp_id!=""){
                                $.ajax({
                                    url:apiurl+"/dailyrecords/temp/"+dailyrecord_temp_id+"",
                                    type:"DELETE",
                                    success:function(d){
                                        var data = JSON.parse(d);
                                        if(data.code=="0"){
                                            if (whichpage == 0) {
                                                //返回添加模版
                                                window.location.href = 'addLogModel.html';
                                            }
                                            else  {
                                                window.location.href='logAdministration.html';
                                            }
                                        }else{
                                            $(".call_back_success").html(data.msg);
                                        }
                                    }
                                });
                            }else{

                                if (whichpage == 0) {
                                    //返回添加模版
                                    window.location.href = 'addLogModel.html';
                                }
                                else  {
                                    window.location.href='logAdministration.html';
                                }
                            }
                        });
                    }else{
                        $(".call_back_success").html(call_back.msg).fadeIn(1000);
                    }
                },
                error:function(d){
                    $(".call_back_success").html(d).fadeIn(1000);
                }
            });
        //}
    });

});